<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JavaScript," />










<meta name="description" content="JavaScript中闭包的理解 1.为什么要了解闭包？ 闭包是js的一个难点也是它的一个特色，是我们必须掌握的js高级特性，那么什么是闭包呢？它又有什么用呢？  我们都知道，js的作用域分两种，全局和局部，基于我们所熟悉的作用域链相关知识，我们知道在js作用域环境中访问变量的权利是由内向外的，内部作用域可以获得当前作用域下的变量并且可以获得当前包含当前作用域的外层作用域下的变量，反之则不能，也就">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript中对闭包的理解">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="JavaScript中闭包的理解 1.为什么要了解闭包？ 闭包是js的一个难点也是它的一个特色，是我们必须掌握的js高级特性，那么什么是闭包呢？它又有什么用呢？  我们都知道，js的作用域分两种，全局和局部，基于我们所熟悉的作用域链相关知识，我们知道在js作用域环境中访问变量的权利是由内向外的，内部作用域可以获得当前作用域下的变量并且可以获得当前包含当前作用域的外层作用域下的变量，反之则不能，也就">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/c_closure.png">
<meta property="article:published_time" content="2022-03-10T12:17:15.000Z">
<meta property="article:modified_time" content="2022-03-11T12:11:55.676Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/c_closure.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/03/10/JavaScript中对闭包的理解/"/>





  <title>JavaScript中对闭包的理解 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JavaScript中对闭包的理解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-03-10T20:17:15+08:00">
                2022-03-10
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/03/10/JavaScript中对闭包的理解/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id><a href="#" class="headerlink" title></a><blockquote class="blockquote-center"><p>JavaScript中闭包的理解</p>
</blockquote></h1><h2 id="1-为什么要了解闭包？"><a href="#1-为什么要了解闭包？" class="headerlink" title="1.为什么要了解闭包？"></a>1.为什么要了解闭包？</h2><ul>
<li><p>闭包是js的一个难点也是它的一个特色，是我们必须掌握的js高级特性，那么什么是闭包呢？它又有什么用呢？</p>
</li>
<li><p>我们都知道，js的作用域分两种，全局和局部，基于我们所熟悉的作用域链相关知识，我们知道在js作用域环境中访问变量的权利是由内向外的，内部作用域可以获得当前作用域下的变量并且可以获得当前包含当前作用域的外层作用域下的变量，反之则不能，也就</p>
<span id="more"></span>

<p>是说在外层作用域下无法获取内层作用域下的变量，同样在不同的函数作用域中也是不能相互访问彼此变量的，那么我们想在一个函数内部也有限权访问另一个函内部的变量该怎么办呢？闭包就是用来解决这一需求的，闭包的本质就是在一个函数内部创建另一个函数。</p>
</li>
<li><p><strong>我们首先知道闭包有3个特性：</strong></p>
<p><strong>①函数嵌套函数</strong></p>
<p><strong>②函数内部可以引用函数外部的参数和变量</strong></p>
<p><strong>③参数和变量不会被垃圾回收机制回收</strong></p>
</li>
</ul>
<h2 id="2-全局变量和局部变量"><a href="#2-全局变量和局部变量" class="headerlink" title="2.全局变量和局部变量"></a>2.全局变量和局部变量</h2><ul>
<li><p><strong>全局变量</strong>：var（关键字）+变量名(标识符)声明的在window里面的变量</p>
<ul>
<li>特点：常驻于内存中，不会被垃圾回收机制回收</li>
<li>优点：在整个js生命周期内，可以正常访问</li>
<li>缺点：由于常驻于内存，可能会导致内存泄漏，以及变量混乱，影响程序局部变量</li>
</ul>
</li>
<li><p><strong>局部变量</strong>：定义在函数内（ES6语法中的let声明的也是局部变量，属于块级作用域），离开定义的函数环境，失去访问权限</p>
<ul>
<li>特点：不会常驻于内存中，会被垃圾回收机制回收，当离开作用域之后失效</li>
<li>优点：不会占用内存</li>
<li>缺点：有时候需要访问的时候，不能正常访问到某个局部变量</li>
</ul>
</li>
<li><p><strong>全局变量与局部变量的例子</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> num = <span class="number">123</span>;			<span class="comment">//定义一个全局变量num</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fun</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    num++;</span><br><span class="line">    <span class="keyword">return</span> num;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fun();                 <span class="comment">//124</span></span><br><span class="line">fun();                 <span class="comment">//125</span></span><br><span class="line"><span class="built_in">console</span>.log(fun());    <span class="comment">//126</span></span><br><span class="line"><span class="built_in">console</span>.log(fun());    <span class="comment">//127</span></span><br></pre></td></tr></table></figure>

<p>由以上代码可以看出，每一次调用fun()的时候，num都会执行<strong>num++<strong>的操作，而基数则是在上一次的保存在内存中的值进行加1，由于num是一个全局变量，常驻内存不消失，因此每次使用num的时候，都是值已经改变的</strong>num</strong>，导致后面使用num的时候出现混乱的情况，作为对比，下面定义一个局部变量num1，执行同样的操作</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fun1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> num1 = <span class="number">123</span>;		<span class="comment">//定义一个局部变量num1</span></span><br><span class="line">    num1++;</span><br><span class="line">    <span class="keyword">return</span> num1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fun1();                 <span class="comment">//124</span></span><br><span class="line">fun1();                 <span class="comment">//124</span></span><br><span class="line"><span class="built_in">console</span>.log(fun1());    <span class="comment">//124</span></span><br><span class="line"><span class="built_in">console</span>.log(fun1());    <span class="comment">//124</span></span><br></pre></td></tr></table></figure>

<p>由以上例子我们可以看出，num1只有在函数fun1内才发生作用，调用fun1()的时候，执行**num1++**的操作，初始值为123，因此能得到值为124，执行玩之后，该变量num1立即被垃圾回收机制回收，不再存在内存中，第二次调用的时候，又重新找操作系统申请了一块内存，用于存另外一个num1的值123，第二次调用的时候，num1的值依然为123而不是124，因为此前的124已经被操作系统回收。因此局部变量永远都只能作用在自己的作用域内。</p>
</li>
<li><p><strong>为了更近一步的证明是不是同一个变量，我决定直接拿到变量的内存地址进行比较</strong></p>
<p>oh，忘记了，由于JavaScript属于高级语言，而且是运行在V8引擎上的，是拿不到变量的内存地址的，默认被const修饰，变量的指针都会指向同一个地方，因此我用C++/C来举例，C++和C都是一样的，反正C++/C语言牛逼，C++/C语言天下无敌就行了（再跟我吹一波C）</p>
<ul>
<li>定义一个全局变量，然后取其地址值；</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">fun</span><span class="params">(<span class="keyword">int</span> num)</span></span>&#123;</span><br><span class="line">	num++;</span><br><span class="line">	cout&lt;&lt;<span class="string">&quot;num的真实内存地址为：&quot;</span>&lt;&lt;&amp;num&lt;&lt;endl; </span><br><span class="line">	<span class="keyword">return</span> num;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">fun</span><span class="params">(<span class="keyword">int</span> num)</span></span>;</span><br><span class="line">	<span class="keyword">int</span> num = <span class="number">123</span>;</span><br><span class="line">	<span class="built_in">fun</span>(num);			<span class="comment">//0x6ffdf0</span></span><br><span class="line">	<span class="built_in">fun</span>(num);			<span class="comment">//0x6ffdf0</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/c_closure.png" class title="C++中num变量的内存地址"></li>
</ul>
<p>​        由上图可知，调用2此fun函数，但是num的地址值依然相同，是同一个，因为num还在内存中，没有被回收</p>
<ul>
<li><p>对于局部变量如下</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">fun</span><span class="params">(<span class="keyword">int</span> a)</span></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> num = <span class="number">123</span>;</span><br><span class="line">	num++;</span><br><span class="line">	cout&lt;&lt;<span class="string">&quot;num的真实内存地址为：&quot;</span>&lt;&lt;&amp;num&lt;&lt;endl; </span><br><span class="line">	<span class="keyword">return</span> num;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">fun</span><span class="params">(<span class="keyword">int</span> num)</span></span>;</span><br><span class="line">	<span class="built_in">fun</span>(<span class="number">1</span>);				<span class="comment">//0x6ffdec</span></span><br><span class="line">	<span class="built_in">fun</span>(<span class="number">1</span>);				<span class="comment">//0x6ffdec</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure></li>
<li><p>这里拿到的值和上面是不一样的，这样也不能更好的说明问题，因为我忘了C/C++并没有垃圾回收机制，变量不会被回收，但是可以知道局部变量和全局变量不是同一个值。将来有好的证明方式会补上。</p>
</li>
</ul>
<h2 id="3-那我再fun函数内想要访问fun2的变量，该怎么办？"><a href="#3-那我再fun函数内想要访问fun2的变量，该怎么办？" class="headerlink" title="3.那我再fun函数内想要访问fun2的变量，该怎么办？"></a>3.那我再fun函数内想要访问fun2的变量，该怎么办？</h2><p><strong>没错，那就是采用闭包的形式</strong></p>
<h3 id="1-那什么是闭包？"><a href="#1-那什么是闭包？" class="headerlink" title="1.那什么是闭包？"></a>1.那什么是闭包？</h3><ul>
<li><p>闭包就是方法嵌套方法，并且被嵌套的方法使用了父方法，父方法的返回值为被嵌套的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fun1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> num = <span class="number">123</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">fun2</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        num++;</span><br><span class="line">        <span class="keyword">return</span> num;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> fun2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> res = fun1();                </span><br><span class="line"><span class="built_in">console</span>.log(res());     <span class="comment">//124</span></span><br><span class="line"><span class="built_in">console</span>.log(res());     <span class="comment">//125 </span></span><br></pre></td></tr></table></figure>

<p>由以上代码可以看出，fun2内部使用了fun1的局部变量num，并且执行了num++的操作，而且fun1的返回值就是fun2函数，因此使用fun1的局部变量的fun2，当在外层使用num的这个值的时候，两个函数因为num的关系形成了闭包，因此两次调用之后的值为124和125；</p>
</li>
</ul>
<h3 id="2-闭包的优点："><a href="#2-闭包的优点：" class="headerlink" title="2.闭包的优点："></a>2.闭包的优点：</h3><ul>
<li>闭包可以使局部变量常驻内存，但是又不会污染全局</li>
</ul>
<h3 id="3-闭包的缺点"><a href="#3-闭包的缺点" class="headerlink" title="3.闭包的缺点"></a>3.闭包的缺点</h3><ul>
<li>变量常驻内存，长时间得不到释放容易导致内存泄露</li>
</ul>
<h3 id="4-闭包解决了什么问题？"><a href="#4-闭包解决了什么问题？" class="headerlink" title="4.闭包解决了什么问题？"></a>4.闭包解决了什么问题？</h3><ul>
<li>闭包可以使闭包函数的局部变量常驻内存，但是又不会污染全局，保护函数内的变量安全 ，实现封装，防止变量流入其他环境发生命名冲突</li>
</ul>
<h2 id="4-使用闭包应该注意什么？"><a href="#4-使用闭包应该注意什么？" class="headerlink" title="4.使用闭包应该注意什么？"></a>4.使用闭包应该注意什么？</h2><ul>
<li>尽可能少的使用闭包</li>
<li>其次由于闭包涉及跨域访问，所以会导致性能损失，我们可以通过把跨作用域变量存储在局部变量中，然后直接访问局部变量，来减轻对执行速度的影响</li>
</ul>
<h2 id="5-写在最后"><a href="#5-写在最后" class="headerlink" title="5.写在最后"></a>5.写在最后</h2><ul>
<li>这里只是简答的对闭包做了一个解释，也是个人理解，更多的文章可以差资料，加油加油！！！！</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2021/11/05/vue%E9%A1%B5%E9%9D%A2%E4%BC%A0%E5%80%BC%E5%92%8C%E4%BC%9A%E8%AF%9D%E5%AD%98%E5%82%A8/" rel="next" title="vue页面传值和会话存储">
                <i class="fa fa-chevron-left"></i> vue页面传值和会话存储
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/03/10/JavaScript%E4%B8%ADthis%E7%9A%84%E7%90%86%E8%A7%A3/" rel="prev" title="JavaScript中this的理解">
                JavaScript中this的理解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">1.</span> <span class="nav-text">JavaScript中闭包的理解
</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E4%BA%86%E8%A7%A3%E9%97%AD%E5%8C%85%EF%BC%9F"><span class="nav-number">1.1.</span> <span class="nav-text">1.为什么要了解闭包？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E5%92%8C%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="nav-number">1.2.</span> <span class="nav-text">2.全局变量和局部变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E9%82%A3%E6%88%91%E5%86%8Dfun%E5%87%BD%E6%95%B0%E5%86%85%E6%83%B3%E8%A6%81%E8%AE%BF%E9%97%AEfun2%E7%9A%84%E5%8F%98%E9%87%8F%EF%BC%8C%E8%AF%A5%E6%80%8E%E4%B9%88%E5%8A%9E%EF%BC%9F"><span class="nav-number">1.3.</span> <span class="nav-text">3.那我再fun函数内想要访问fun2的变量，该怎么办？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E9%82%A3%E4%BB%80%E4%B9%88%E6%98%AF%E9%97%AD%E5%8C%85%EF%BC%9F"><span class="nav-number">1.3.1.</span> <span class="nav-text">1.那什么是闭包？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E9%97%AD%E5%8C%85%E7%9A%84%E4%BC%98%E7%82%B9%EF%BC%9A"><span class="nav-number">1.3.2.</span> <span class="nav-text">2.闭包的优点：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E9%97%AD%E5%8C%85%E7%9A%84%E7%BC%BA%E7%82%B9"><span class="nav-number">1.3.3.</span> <span class="nav-text">3.闭包的缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E9%97%AD%E5%8C%85%E8%A7%A3%E5%86%B3%E4%BA%86%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%EF%BC%9F"><span class="nav-number">1.3.4.</span> <span class="nav-text">4.闭包解决了什么问题？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E4%BD%BF%E7%94%A8%E9%97%AD%E5%8C%85%E5%BA%94%E8%AF%A5%E6%B3%A8%E6%84%8F%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-number">1.4.</span> <span class="nav-text">4.使用闭包应该注意什么？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E5%86%99%E5%9C%A8%E6%9C%80%E5%90%8E"><span class="nav-number">1.5.</span> <span class="nav-text">5.写在最后</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/03/10/JavaScript%E4%B8%AD%E5%AF%B9%E9%97%AD%E5%8C%85%E7%9A%84%E7%90%86%E8%A7%A3/';
          this.page.identifier = '2022/03/10/JavaScript中对闭包的理解/';
          this.page.title = 'JavaScript中对闭包的理解';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
